/*
 * @lc app=leetcode.cn id=110 lang=cpp
 *
 * [110] 平衡二叉树
 */

#include "include.h"

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // use node->val to store the level of the sub tree ...
    std::stack<TreeNode*> nodePtrStack_;

    bool isBalanced(TreeNode* root) {
        // std::stack<int> level;
        // std::stack<TreeNode*> nodePtr;

        levelOrderTraverse(root);

        while (!nodePtrStack_.empty()){
            TreeNode* lastNodePtr = nodePtrStack_.top();
            nodePtrStack_.pop();

            int leftSubTreeLevel = lastNodePtr->left ? lastNodePtr->left->val : 0;
            int rightSubTreeLevel = lastNodePtr->right ? lastNodePtr->right->val : 0;

            int balanceFactor = leftSubTreeLevel - rightSubTreeLevel;
            if (std::abs(balanceFactor) > 1){return false;}

            lastNodePtr->val = std::max(leftSubTreeLevel, rightSubTreeLevel) + 1;
            // for test
            // printf("( %d %d %d %d)", lastNodePtr->val, balanceFactor, leftSubTreeLevel, rightSubTreeLevel); 
        }
        // for test
        // printf("\n");
        return true;
    }

    void levelOrderTraverse(TreeNode* root) {
        if (!root) {return;}
        std::queue<TreeNode*> nodePtrQueue;
        nodePtrQueue.push(root);
        while (!nodePtrQueue.empty())
        {
            TreeNode* topNodePtr = nodePtrQueue.front();
            nodePtrQueue.pop();

            // put it into stack to reverse level order traverse
            nodePtrStack_.push(topNodePtr);

            // for test
            // printf("%d ", topNodePtr->val);

            if (topNodePtr->left) {nodePtrQueue.push(topNodePtr->left);}
            if (topNodePtr->right) {nodePtrQueue.push(topNodePtr->right);}
        }
        // for test
        // printf("\n");
    }
};
// @lc code=end

class SolutionLC {
public:
    int height(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        int leftHeight = height(root->left);
        int rightHeight = height(root->right);
        if (leftHeight == -1 || rightHeight == -1 || abs(leftHeight - rightHeight) > 1) {
            return -1;
        } else {
            return max(leftHeight, rightHeight) + 1;
        }
    }

    bool isBalanced(TreeNode* root) {
        return height(root) >= 0;
    }
};

